package com.ruike.alisurface.services;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.IntentService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.ui.mainPage.VedioAdvActivity;
import com.ruike.alisurface.utils.ScreenshotsUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.ThreadUtils;
import com.voodoo.lib_frame.base.BaseView;
import com.voodoo.lib_frame.httpTools.ApiTools;
import com.voodoo.lib_frame.httpTools.RequestParams;
import com.voodoo.lib_frame.manager.FActivityManager;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import java.io.File;
import java.util.List;

/**
 * 截屏信息下载类
 */
public class MyScrennService extends IntentService implements BaseView {
    public final String Tag = "上传截屏信息=";

    ApiTools apiTools = new ApiTools();//网络上传对象
    File file;//文件
    Bitmap bitmap1 = null;//位图

    public MyScrennService() {
        super("MyScrennService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        L.i(Tag + "MyScrennService===");
    }

    /**
     * 判断当前应用程序处于前台还是后台  true  后台  false  前台
     */
    public boolean isApplicationBroughtToBackground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            @SuppressLint({"NewApi", "LocalSuppress"}) ComponentName topActivity = tasks.get(0).topActivity;
            return !topActivity.getPackageName().equals(context.getPackageName());
        }
        return false;
    }

    /**
     * 截图并上传
     */
    public void getConfirm_cmd() {
        if (!isApplicationBroughtToBackground(this)) {
            String url1 = Constant.HttpUrl.url_cmd + "/MchAdminApi/confirm_cmd";
            RequestParams params = new RequestParams();
            params.put("cmd_id", ShareUtils.getInstance().getString("cmd_id", ""));
            apiTools.getRequest(url1, params, this);

            L.i(Tag + "MyScrennService===", FActivityManager.getInstance().getTopActivity());
            if (FActivityManager.getInstance().getTopActivity() instanceof VedioAdvActivity) {
                int types = ShareUtils.getInstance().getInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_IMAGE);
                L.i(Tag + "MyScrennService===", types);
                if (types == 1) {
                    ThreadUtils.postUI(new Runnable() {
                        @Override
                        public void run() {
                            bitmap1 = ((VedioAdvActivity) FActivityManager.getInstance().getTopActivity()).getTxVedioBitmap();
                            L.i(Tag + "MyScrennService==222=", bitmap1);
                            saveBitmapSend();
                            return;
                        }
                    });
                } else {
                    bitmap1 = ScreenshotsUtils.
                            activityShot(FActivityManager.getInstance().getTopActivity());
                }
            } else {
                bitmap1 = ScreenshotsUtils.
                        activityShot(FActivityManager.getInstance().getTopActivity());
            }
            saveBitmapSend();

        } else {
            L.i(Tag + "不在前台不截图");
        }

    }

    /**
     * 上传图片
     */
    public void saveBitmapSend() {
        ThreadUtils.post(new Runnable() {
            @Override
            public void run() {
                if (bitmap1 != null) {
                    file = ScreenshotsUtils.saveBitmap(bitmap1);
                    L.i(Tag + "上传截屏信息图片===" + file.getAbsolutePath());
                    String url = Constant.HttpUrl.url_cmd + "/MchApi/AddScreenshot";
                    RequestParams params1 = new RequestParams();
                    params1.put("mchid", ShareUtils.getInstance().getString(ShareKey.MCH_ID, ""));
                    params1.put("cmd_id", ShareUtils.getInstance().getString("cmd_id", ""));
                    params1.put("file", file);
                    apiTools.postRequest(url, params1, MyScrennService.this);
                }
            }
        });

    }

    @Override
    protected void onHandleIntent(Intent intent) {

        try {

            getConfirm_cmd();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        apiTools.CallCancal("");
    }


    /**
     * ================================================================================================
     */
    @Override
    public void onStarted(String loadingStr) {

    }

    @Override
    public void onLoading(long total, long current) {

    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onErrorTip(String errorStr) {

    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {

        if (requestUrl.endsWith("confirm_cmd")) {

            L.i(Tag + "confirm_cmd=onSuccess==" + requestJsonStr);

        } else if (requestUrl.endsWith("AddScreenshot")) {
            try {
                if (file != null && file.exists()) {
                    file.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            L.i(Tag + " 图片 AddScreenshot=onSuccess==" + requestJsonStr);
        }

    }

    @Override
    public void onFailure(String requestUrl, String requestMsg) {

    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        if (requestUrl.endsWith("confirm_cmd")) {
            L.i(Tag + "confirm_cmd=onFailed==" + errorMsg);
        } else if (requestUrl.endsWith("AddScreenshot")) {
            L.i(Tag + " 截屏信息图片   AddScreenshot=onError==" + errorMsg);
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg, String data) {

    }

    @Override
    public void onException(Exception exception) {

    }

    @Override
    public void onDownloadFailed(String requestUrl, Exception e) {

    }

    @Override
    public void onDownloadSuccess(String requestUrl, File file) {

    }

    @Override
    public void onDownloading(String requestUrl, long total, long progress) {

    }
}